package demo.practice.leetcode_eveyday;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class P1482 {


    public static void main(String[] args) {
        P1482 p1482 = new P1482();
        p1482.minDays(new int[]{1, 10, 2, 9, 3, 8, 4, 7, 5, 6}, 2, 3);
    }

    public int minDays(int[] bloomDay, int m, int k) {
        if (k * m > bloomDay.length)
            return -1;

        List<Integer> list = new ArrayList<>();
        for (int index = 0; index < bloomDay.length; index++) {
            list.add(index);
        }
        Collections.sort(list, (o1, o2) -> bloomDay[o1] - bloomDay[o2]);

        int[] blooms = new int[bloomDay.length];

        int day;
        for (int i = 0; i < list.size(); i++) {
            blooms[list.get(i)] = 1;
            day = bloomDay[list.get(i)];
            if (i + 1 >= m * k && check(blooms, m, k)) {
                return day;
            }
        }

        return -1;
    }

    /**
     * @param blooms
     * @param m      多少束花
     * @param k      每份需要 连续多少多花
     * @return
     */
    private boolean check(int[] blooms, int m, int k) {
        if (k == 1)
            return true;

        int count = 0;
        for (int bloom : blooms) {
            if (bloom == 1) {//说明有花
                count++;
                if (count == k) {
                    //满了一束花
                    if (--m <= 0)
                        return true;
                    count = 0;
                }
                if (k <= 0)//提前判断一下
                    return true;

            } else {//说明断了
                count = 0;
            }
        }
        return m<= 0;    //说明花已经全部
    }

}
